layui.use(['element'], function () {
    var $ = layui.jquery;
    $(document).ready(function () {
        $('a[data-group]').click(function () {
            $(this).siblings().removeClass("now");
            $(this).addClass("now");
            renderCalendar($);
        });

        $('.layui-tab-title li').click(function () {
            $(this).siblings().removeClass("layui-this");
            $(this).addClass("layui-this");
            renderCalendar($);
        });

        renderCalendar($);
    });
    $(document).resize(function () {
        renderCalendar($);
    });
});

function renderCalendar($) {
    let celendarHeight = $(window).height()-$('.timo-card-header').height() - $('.layui-tab-title').height()-50;
    let groupId = $('a[data-group].now').attr('data-group');
    let date = $('.layui-tab-title li.layui-this').attr('lay-id');
    // console.log(groupId+"=="+date);
    var options = {
        headerToolbar: false, // 不显示头部按钮
        // locale: 'zh-cn', // 语言
        initialView: 'resourceTimelineDay',
        schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',
        // Fullcalendar的日程调度timeline插件属于增值功能，意思是属于高级功能要貌似要收费，
        // 但是用户可以将该插件用在非营利性项目中。使用timeline插件默认会在页面左下角有版权信息，
        // 但是我们可以将一个参数schedulerLicenseKey的值设置为'GPL-My-Project-Is-Open-Source'就可隐藏左下角的版权内容。
        slotLabelFormat: {
            hour: 'numeric',
            minute: '2-digit',
            omitZeroMinute: false, // 分钟是0时，是否把分钟去除？
            omitCommas:true,
            hour12: false,
        },
        initialDate: date,
        slotDuration: '00:15:00', // 显示时间间隔，默认'00:30:00'，即30分钟。
        slotMinTime:"07:00:00",
        slotMaxTime:"22:00:00",
        resourceAreaHeaderContent: '会议室', // 纵轴的第一行 用来表示纵轴的名称
        resourceAreaWidth: '20%',
        height: celendarHeight,
        resources: '/meeting/order/room/list?groupId='+groupId, // 日历左侧第一列，会议室列表
        events: '/meeting/order/room/orders?groupId='+groupId, // 日历右侧主体事件数据
        selectable: true,
        editable: false,
        resourceLabelDidMount: function(arg) {//颜色设置
            if(arg.resource.extendedProps && arg.resource.extendedProps.color) {
                arg.el.style.backgroundColor = arg.resource.extendedProps.color;
            }
        },
        select: selectedRange,//选择时间范围后的操作
        eventClick: showDetail,//点击预订信息后的操作
        eventMouseEnter:function (event,view) {//鼠标移到预订信息上时的事件：显示详细标题信息
            let content = event.event.title;
            content = content.replace(/ - /ig,'<br>');
            $(".tips").html(content).css({left:event.jsEvent.clientX+10,top:event.jsEvent.clientY+2}).show();
        },
        eventMouseLeave:function (event,view) {//鼠标移开时的事件
            $(".tips").text('').hide();
        }
    };

    var calendarEl = document.getElementById('grid');
    let calendar = new FullCalendar.Calendar(calendarEl, options);
    calendar.render();
}

function selectedRange(selectInfo) {
    var $ = layui.jquery;
    //弹出会议预订的窗口
    $.post('/meeting/order/room/takeing', {'roomId': selectInfo.resource.id,'start':selectInfo.start,'end':selectInfo.end}, function (msg) {
        if (msg.code==200) {
            //打开编辑页面
            let url = '/meeting/order/room/take?newFlag=1&orderId='+msg.data.id;
            window.layerIndex = layer.open({
                type: 2,
                title: '预订会议室',
                shadeClose: true,
                maxmin: true,
                area: ['630px', '430px'],
                content: [url, 'on'],
                success: function(layero, index){
                    let doc = $('body').find("iframe")[0].contentWindow.document;
                    window.subject = doc.getElementById("subject").value;
                    window.userName = doc.getElementById("userName").value;
                    $(doc).find('.ajax-post').click(function () {
                        window.subject = doc.getElementById("subject").value;
                        window.userName = doc.getElementById("userName").value;
                    });
                },
                end:function () {
                    let startT = selectInfo.startStr.split('T')[1].substring(0,5);
                    let endT = selectInfo.endStr.split('T')[1].substring(0,5);
                    selectInfo.view.calendar.addEvent({
                        resourceId:msg.data.meetingId,
                        id:msg.data.id,
                        title: window.userName + ' - ' + window.subject + ' - ' + startT + " ~ " + endT,
                        start: selectInfo.start,
                        end: selectInfo.end,
                        allDay: selectInfo.allDay
                    });
                    selectInfo.view.calendar.unselect();
                }
            });
        } else {
            layer.alert(msg.msg, {area: ['600px', '400px'],offset: '15px', icon: 1,btn:['知道了']},function (index) {
                layer.close(index);
            });
        }
    });
}

/**
 * 查看会议预订的详细情况
 * @param info
 */
function showDetail(info) {
    var $ = layui.jquery;
    $.post('/meeting/order/is_self',{'orderId':info.event.id},function (ret) {
        if(ret && ret.code==200){//如果正常返回
            if(ret.data==true){//如果是自己，则提示要不要取消预订
                //应用出现修改页面
                let url = '/meeting/order/room/take?orderId='+info.event.id;
                window.layerIndex = layer.open({
                    type: 2,
                    title: '修改预订信息',
                    shadeClose: true,
                    maxmin: true,
                    area: ['630px', '430px'],
                    content: [url, 'on'],
                    btn:['取消预订'],
                    btn1:function () {
                        cancelMeeting(info);
                        layer.close(window.layerIndex);
                    },
                    end:function () {
                        renderCalendar(layui.jquery);
                    }
                });
            }else{//查看详情
                layer.open({
                    type: 2,
                    title: '预订会议室',
                    shadeClose: true,
                    maxmin: true,
                    area: ['50%', '80%'],
                    content: ['/meeting/order/detail/'+info.event.id, 'on']
                });
            }
        }else{
            layer.alert(msg.msg, {area: ['600px', '400px'],offset: '15px', icon: 1,btn:['知道了']},function (index) {
                layer.close(index);
            });
        }
    });
}

function cancelMeeting(info) {
    layer.confirm('取消该会议预约吗？', {
        title: '提示',
        btn: ['是的', '关闭']
    }, function () {
        var $ = layui.jquery;
        $.post('/meeting/order/cancel',{'orderId':info.event.id}, function (result) {
            if(result && result.code==200){
                info.event.remove();
                layer.msg('取消成功！');
            }else{
                layer.alert(result.msg, {area: ['600px', '400px'],offset: '15px', icon: 1,btn:['知道了']},function (index) {
                    layer.close(index);
                });
            }
        });
    });
}